﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace DusonFramework.Documents.Office.Word
{
    public class WordHelper
    {
        public static string GetClipboardData()
        {
            var data = Clipboard.GetDataObject();

            if (data == null)
                throw new Exception("剪切板无数据，请从wps6.0+ word文档复制您想要转换的内容！");

            string[] formats = data.GetFormats();

            if (!formats.Contains("Kingsoft WPS 6.0 Format"))
                throw new Exception("剪切板数据格式不正确，请从wps6.0+ word文档复制您想要转换的内容！");

            System.IO.MemoryStream ms = (System.IO.MemoryStream)data.GetData("Html Format");
            if (ms == null)
                throw new Exception("剪切板数据格式不正确，请从wps6.0+ word文档复制您想要转换的内容！");

            string html = System.Text.Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();

            string pattern = "<!--StartFragment-->(?<FirstGroup>(.|\n)+?)<!--EndFragment-->";

            GroupCollection gc = null;
            Match match = Regex.Match(html, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
            if (match.Success && match.Groups.Count > 0)
                gc = match.Groups;

            if (gc != null && gc["FirstGroup"] != null)
            {
                html = gc["FirstGroup"].Value;
            }

            // 过滤掉 style="xxx" 和 class="xxx"
            html = System.Text.RegularExpressions.Regex.Replace(html, @"\s*(style|class|valign|width)=""[^""]+""", "", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            // 过滤掉 style=xxx 和 class=xxx
            html = System.Text.RegularExpressions.Regex.Replace(html, @"\s*(style|class|valign|width)=[^\s>]+", "", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            // 过滤掉空格
            html = System.Text.RegularExpressions.Regex.Replace(html, @"\s+>", ">", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            // 过滤无用的html标签
            html = html.Replace("<o:p></o:p>", "").Replace("<span></span>", "").Replace("<p></p>", "");

            return html;
        }
    }
}
